package com.supor.aiot;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Message;
import android.os.SystemClock;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.mobile.framework.quinoxless.QuinoxlessFramework;
import com.android.baseconfig.base.AndroidWorkaround;
import com.android.baseconfig.base.BaseHandler;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.helper.ActivityManager;
import com.android.baseconfig.common.helper.NetConnectionReceiver;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.mpaas.mas.adapter.api.MPLogger;
import com.supor.aiot.basket.ui.basket.BasketFragment;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.AppInit;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporApplication;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.entity.LaunchPageBean;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.utils.ScreenSiazeUtils;
import com.supor.aiot.databinding.ActivityMainBinding;
import com.supor.aiot.food.ui.food.FoodFragment;
import com.supor.aiot.helper.LaunchPageHelper;
import com.supor.aiot.helper.PrivacyProtocolHelper;
import com.supor.aiot.home.helper.DataCache;
import com.supor.aiot.home.ui.home.HomeFragment;
import com.supor.aiot.mine.ui.mine.MineFragment;
import com.supor.aiot.ui.privacy.AuthPrivacyActivity;
import com.supor.aiot.ui.privacy.SplashActivity;
import com.supor.nfc.lib.utils.NfcUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;

import io.reactivex.rxjava3.functions.Consumer;

import static com.supor.aiot.common.app.AppAgent.h5Debug;
import static com.supor.aiot.common.app.Constants.SETTING_GPS;

public class MainActivity extends BaseMVVMActivity<NoViewModel, ActivityMainBinding>
        implements BaseHandler.BaseHandlerCallBack, SensorEventListener {
    private HomeFragment homeFragment;
    private Fragment foodFragment;
    private Fragment basketFragment;
    private Fragment communityFragment;
    private Fragment myFragment;
    private Fragment mCurrentFragment;
    private List<Fragment> fragmentList;
    private NetConnectionReceiver connectionReceiver;
    private PrivacyProtocolHelper privacyProtocolHelper;
    private BaseHandler<BaseHandler.BaseHandlerCallBack> handler;
    private LaunchPageBean launchPageBean = null;
    private AtomicBoolean ifShowImg = new AtomicBoolean(false);
    /**
     * 是否已经按下返回键
     */
    private AtomicBoolean backPressed = new AtomicBoolean(false);

    int INDEX = 0;
    public static final int HOME = 0x1;
    public static final int FOOD = 0x2;
    public static final int BASKET = 0x3;
    public static final int MY = 0x4;
    private LaunchPageHelper launchPageHelper;
    private TranslateAnimation hiddenAction;
    /**
     * 是否首次打开APP，默认1表示首次打开，0表示非首次
     */
    private int firstOpenApp;
    /**
     * 是否需要显示权限页面，默认0表示需要显示，1表示已经申请过不需要显示
     */
    private int authPrivacyPolicy;

    //定义sensor管理器
    private SensorManager mSensorManager;
    //震动
    private Vibrator vibrator;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        SystemUtils.isNavigationBarExist(this, (isShowing, b) -> {
            Logc.i("onNavigationState= " + isShowing + ", b= " + b);
            AppAgent.isNavigationBarExist = isShowing;
            if (isShowing) {
                AndroidWorkaround.assistActivity(this, b);
            } else {
                AndroidWorkaround.assistActivity(this, 0);
            }
        });
        handler = new BaseHandler<>(this);
        launchPageHelper = new LaunchPageHelper(this);
        super.onCreate(savedInstanceState);

        RxBus3.getInstance().register(Constants.Tag.HOME_PAGE, (Consumer<Integer>) index -> {
            if (index != null) {
                checkTab(index);
                INDEX = 0;
            }
        }, getClass());
        RxBus3.getInstance().register(Constants.Tag.ACTIVITY_RESUMED, (Consumer<Activity>) activity -> {
            try {
                Activity pauseActivity = AppAgent.getPauseActivity();
                if ("H5Activity".equalsIgnoreCase(activity.getClass().getSimpleName())
                        && (pauseActivity != null && "H5Activity".equalsIgnoreCase(pauseActivity.getClass().getSimpleName()))) {
                    SuporPresenter.getInstance().reportShareChannel();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, getClass());

        //震动
        vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
        registerSensor();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        System.out.println("main_container_debug:" + bindingView.layout.getWidth() + "*" + bindingView.layout.getHeight());
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public int resourceId() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean isUseBlackFontWithStatusBar() {
        return false;
    }

    @Override
    protected void initData() {
        super.initData();

        fragmentList = new ArrayList<>();
        fragmentList.add(homeFragment = HomeFragment.newInstance());
        fragmentList.add(foodFragment = FoodFragment.newInstance());
        fragmentList.add(basketFragment = BasketFragment.newInstance());
        // fragmentList.add(communityFragment = (Fragment) ARouter.getInstance().build(PathUrl.PATH_FRAGMENT_COMMUNITY).navigation());
        fragmentList.add(myFragment = MineFragment.newInstance());
        initEvent();

        // 设置mPaaS用户ID，退出有清除
        if (QuinoxlessFramework.initSuccess()) {
            if (GlobalDataCache.userInfo != null) {
                MPLogger.setUserId(h5Debug ? "123456" : GlobalDataCache.userInfo.getBossUserId());
            } else {
                MPLogger.setUserId(h5Debug ? "123456" : "userid_android");
            }
        }
        NfcUtils.NfcCheck(this);
        DataCache.getGIZIp();

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(dm);
        AppAgent.smallScreen = dm.widthPixels <= 1080;
        AppAgent.heightPixels = dm.heightPixels;
        AppAgent.density = dm.density;
        ScreenSiazeUtils screenSiazeUtils = new ScreenSiazeUtils();
        Logc.i("widthPixels= " + dm.widthPixels + ", heightPixels= " + dm.heightPixels
                + " NavigationBar=" + screenSiazeUtils.getNavigationBarHeight(this)
                + " ScreenRealHeight=" + screenSiazeUtils.getScreenRealHeight(this)
                + " ScreenHeight=" + screenSiazeUtils.getScreenHeight(this)
                + " NavigationBarIsShow=" + screenSiazeUtils.getNavigationBarIsShow(this)
                + " NavigationBarIsShowWithRes=" + screenSiazeUtils.getNavigationBarIsShowWithRes(this)
        );
        Logc.i("density= " + dm.density);

        int screenWidth = dm.widthPixels; // 获取屏幕宽度
        ViewGroup.LayoutParams lp = bindingView.img.getLayoutParams();
        lp.width = screenWidth;
        lp.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        bindingView.img.setLayoutParams(lp);


        int tpHeight;
        if (screenSiazeUtils.isAllScreenDevice(this)) {
            // The full screen needs to get the height through this method
            tpHeight = screenSiazeUtils.getScreenRealHeight(this);
        } else {
            tpHeight = screenSiazeUtils.getScreenHeight(this);
        }
        tpHeight = Math.min(screenWidth * 2, tpHeight - getResources().getDimensionPixelOffset(R.dimen.dp_160));

        bindingView.img.setMaxWidth(screenWidth);
        bindingView.img.setMaxHeight(tpHeight);

//        RelativeLayout.LayoutParams
//                layoutParams = (RelativeLayout.LayoutParams) bindingView.ivSplashBg.getLayoutParams();
//        layoutParams.bottomMargin = -screenSiazeUtils.getNavigationBarHeight(this);

//        bindingView.img.setMaxHeight(Math.min(screenWidth * 2, dm.heightPixels - getResources().getDimensionPixelOffset(R.dimen.dp_104)));

        handler.sendEmptyMessageDelayed(3, 100);
        registerReceiver();

        privacyProtocolHelper = new PrivacyProtocolHelper(this);

        firstOpenApp = BaseSharedPreferences.getInt(SuporApplication.getInstance(),
                Constants.Key.param_firstOpenApp, 1);
        authPrivacyPolicy = BaseSharedPreferences.getInt(SuporApplication.getInstance(),
                Constants.Key.param_authPrivacyPolicy, 0);

        // 获取启动图更新
        handler.sendEmptyMessageDelayed(1, 500);
        hiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, -1.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f);
        hiddenAction.setDuration(300);

    }

    private void checkTab(int index) {
        switch (index) {
            case HOME:
                bindingView.rgTab.check(R.id.rb_home);
                break;
            case FOOD:
                bindingView.rgTab.check(R.id.rb_food);
                break;
            case BASKET:
                bindingView.rgTab.check(R.id.rb_basket);
                break;
            case MY:
                bindingView.rgTab.check(R.id.rb_mine);
                break;
            default:
                break;
        }
    }

    protected void initEvent() {
        bindingView.rgTab.setOnCheckedChangeListener((group, checkedId) -> {
            int index = HOME;
            switch (checkedId) {
                case R.id.rb_home:
                    index = HOME;
                    // setStatusBarColor(true);
                    break;
                case R.id.rb_food:
                    index = FOOD;
                    // setStatusBarColor(true);
                    break;
                case R.id.rb_basket:
                    index = BASKET;
                    // setStatusBarColor(true);
                    break;
                case R.id.rb_mine:
                    index = MY;
                    // setStatusBarColor(true);
                    break;
                default:
                    break;
            }
            setFragment(index);
        });
        setFragment(HOME);
    }

    private void setFragment(int index) {
        GlobalDataCache.homeIndex = index;
        final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment nextFragment = fragmentList.get(index - 1);
        if (mCurrentFragment == null) {
            ft.add(R.id.layout, mCurrentFragment = nextFragment);
            ft.setMaxLifecycle(nextFragment, Lifecycle.State.RESUMED);
        } else {
            if (mCurrentFragment == nextFragment) {
                return;
            }
            if (nextFragment.isAdded()) {
                ft.hide(mCurrentFragment);
                ft.setMaxLifecycle(mCurrentFragment, Lifecycle.State.STARTED);
                ft.show(mCurrentFragment = nextFragment);
                ft.setMaxLifecycle(nextFragment, Lifecycle.State.RESUMED);
            } else {
                ft.hide(mCurrentFragment);
                ft.setMaxLifecycle(mCurrentFragment, Lifecycle.State.STARTED);
                ft.add(R.id.layout, mCurrentFragment = nextFragment);
                ft.setMaxLifecycle(nextFragment, Lifecycle.State.RESUMED);
            }
        }
        ft.commitAllowingStateLoss();
    }

    @Override
    public void callBack(Message msg) {
        switch (msg.what) {
            case 0:
                if (!MainActivity.this.isDestroyed()) {
                    checkPrivacy();
                }
                break;
            case 1:
                // 获取启动图更新
                downloadLaunchPage((bitmap, bean) -> runOnUiThread(() -> {
                    if (ifShowImg.get()) {
                        return;
                    }
                    handler.removeMessages(2);
                    if (bean != null) {
                        launchPageBean = bean;
                    }
                    showImg(bitmap);
                    handler.sendEmptyMessageDelayed(0, 3000);
                }));
                // 最长等待3s
                handler.sendEmptyMessageDelayed(2, 3000);
                break;
            case 2:
                ifShowImg.set(true);
                showImg(getCacheLaunchPage());
                handler.sendEmptyMessageDelayed(0, 3000);
                break;
            case 3:
                // 初始化一键登录
                ThreadUtils.execute(() -> {
                    while (!QuinoxlessFramework.initSuccess() || !SuporPresenter.initSuccess()) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (QuinoxlessFramework.initSuccess() && SuporPresenter.getInstance().getCmccHelper() == null) {
                        runOnUiThread(() -> SuporPresenter.getInstance().initCmcc(MainActivity.this));
                    }
                });
                break;
            default:
                break;
        }
    }

    /**
     * 首次打开APP进去引导页和权限配置页
     */
    private void checkPrivacy() {
        Logc.i("checkPrivacy");
        if (MainActivity.this.isDestroyed()) {
            return;
        }
        if (authPrivacyPolicy == 0) {
            SuporApplication.getInstance().mainHandler.postDelayed(()
                    -> {
                startActivityForResult(new Intent(MainActivity.this,
                        AuthPrivacyActivity.class), Constants.FIRST_PRIVACY);
                overridePendingTransition(com.android.baseconfig.R.anim.activity_open_enter, 0);
            }, 10);
            // SuporApplication.getInstance().mainHandler.postDelayed(this::hideStartPage, 500);
        } else if (firstOpenApp == 1) {
            SuporApplication.getInstance().mainHandler.postDelayed(()
                    -> {
                startActivityForResult(new Intent(MainActivity.this,
                        SplashActivity.class), Constants.FIRST_PRIVACY);
                overridePendingTransition(com.android.baseconfig.R.anim.activity_open_enter, 0);
            }, 10);
            // SuporApplication.getInstance().mainHandler.postDelayed(this::hideStartPage, 500);
        } else {
            hideStartPage();
            // checkPermission();
            checkPrivacyUpdate(5000);
        }
    }

    private void checkPrivacyUpdate(int time) {
        ThreadUtils.execute(() -> {
            if (MainActivity.this.isDestroyed()) {
                return;
            }
            privacyProtocolHelper.checkUpdate();
        }, time);
    }

    /**
     * 显示启动图
     *
     * @param bitmap
     */
    private void showImg(Bitmap bitmap) {
        if (bitmap != null) {
            bindingView.img.setImageBitmap(bitmap);
            String launchPageStr =
                    BaseSharedPreferences.getString(MainActivity.this,
                            Constants.Key.LAUNCH_PAGE_INFO);
            if (!TextUtils.isEmpty(launchPageStr)) {
                launchPageBean =
                        GsonUtil.getInstance().toObject(launchPageStr,
                                LaunchPageBean.class);
            }
        }
        bindingView.img.setVisibility(View.VISIBLE);
        bindingView.img.setOnClickListener(imgClickListener);
    }

    private View.OnClickListener imgClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bindingView.img.setClickable(false);
            if (firstOpenApp == 1 || authPrivacyPolicy == 0 || GlobalDataCache.ifNfcPop) {
                return;
            }
            // 是否需要跳转: 1-跳转
            if (launchPageBean != null && "1".equalsIgnoreCase(launchPageBean.needJump)) {
                hideStartPage();
                handler.removeCallbacks(null);
                handler.removeMessages(0);
                handler.removeMessages(1);
                handler.removeMessages(1);
                Logc.i("onClick startTiny");
                String type = null;
                if ("4".equalsIgnoreCase(launchPageBean.urlType)) {
                    type = "PB";
                }
                AppAgent.startRecipePage(launchPageBean.redirectUrl, type);
            }
        }
    };

    private void hideStartPage() {
        if (bindingView.rlWelcome.getVisibility() != View.GONE) {
            bindingView.rlWelcome.startAnimation(hiddenAction);
            bindingView.rlWelcome.setVisibility(View.GONE);
        }
        bindingView.rlWelcome.postDelayed(() -> SuporPresenter.getInstance().reportNFCParams(GlobalDataCache.NFC_PARAMS), 300);
        homeFragment.hidePage();
        setStatusBarColor(true);
    }

    public void downloadLaunchPage(LaunchPageHelper.LaunchPageCallback callback) {
        if (launchPageHelper != null) {
            launchPageHelper.downloadLaunchPage(callback);
        }
    }

    public Bitmap getCacheLaunchPage() {
        if (launchPageHelper != null) {
            return launchPageHelper.getCacheLaunchPage();
        }
        return null;
    }

    public Bitmap getCacheLaunchPage(String picId) {
        if (launchPageHelper != null) {
            return launchPageHelper.getCacheLaunchPage(picId);
        }
        return null;
    }

    private void registerReceiver() {
        if (connectionReceiver == null) {
            connectionReceiver = new NetConnectionReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
            filter.addAction(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
            registerReceiver(connectionReceiver, filter);
        }
    }

    private void unregisterReceiver() {
        if (connectionReceiver != null) {
            unregisterReceiver(connectionReceiver);
            connectionReceiver = null;
        }
    }

    @Override
    public void updateNetStatus(int type) {

    }

    private void registerSensor() {
        if (mSensorManager == null) {
            //获取传感器管理服务
            mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        }
        //加速度传感器
        mSensorManager.registerListener(this,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                //还有SENSOR_DELAY_UI、SENSOR_DELAY_FASTEST、SENSOR_DELAY_GAME等，
                //根据不同应用，需要的反应速率不同，具体根据实际情况设定
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    private void unregisterSensor() {
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }
    }

    long shakeTime = SystemClock.uptimeMillis();

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (AppAgent.isSwitchBackground()) {
            return;
        }
        int sensorType = event.sensor.getType();
        float[] values = event.values;
        // x轴方向的重力加速度，向右为正
        float x = values[0];
        // y轴方向的重力加速度，向前为正
        float y = values[1];
        // z轴方向的重力加速度，向上为正
        float z = values[2];
        if (sensorType == Sensor.TYPE_ACCELEROMETER) {
            // Logc.e("onSensorChanged: x: " + x + ", y: " + y);
            // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
            // 如果不敏感请自行调低该数值,低于10的话就不行了,因为z轴上的加速度本身就已经达到10

            int minValue = 20;
            // if (MarketUtils.BRAND.VIVO_BRAND.equalsIgnoreCase(Build.BRAND)) {
            //     minValue = 45;
            // }
            if ((Math.abs(x) > minValue || Math.abs(y) > minValue)) {

                // 间隔1s处理一次，防止频繁触发
                if (SystemClock.uptimeMillis() - shakeTime > 1000) {
                    continuousShake();
                }

            }
        }
    }

    /**
     * 点击次数
     */
    final static int COUNTS = 3;
    /**
     * 规定有效时间
     */
    final static long DURATION = 1000;
    long[] mHits = new long[COUNTS];

    private void continuousShake() {
        //每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION) && AppInit.isAppInited) {
            Logc.i("####: -------------------------------------");
            //重新初始化数组
            mHits = new long[COUNTS];
            //执行逻辑
            vibrator.vibrate(VibrationEffect.createWaveform(new long[]{200, 200},
                    -1));
            ARouter.getInstance().build(PathUrl.PATH_INTO_SEARCH)
                    .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                            com.android.baseconfig.R.anim.activity_open_exit)
                    .navigation(AppAgent.getCurrentActivity());
            shakeTime = SystemClock.uptimeMillis();
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    protected void onStop() {
        super.onStop();
        ifShowImg.set(false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null != communityFragment) {
            communityFragment.onActivityResult(requestCode, resultCode, data);
        }
        if (requestCode == Constants.FIRST_PRIVACY) {
            if (resultCode == 0) {
                finish();
            } else {
                hideStartPage();
                // checkPermission();
            }
        } else if (requestCode == SETTING_GPS) {
            homeFragment.onActivityResult(requestCode, resultCode, data);
        }
        Logc.i("onActivityResult: requestCode: " + requestCode + ", resultCode: " + resultCode);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterSensor();
        if (QuinoxlessFramework.initSuccess()) {
            MPLogger.setUserId(null);
        }
        AppAgent.isShowCmcc = false;
        SuporPresenter.getInstance().onDestroy();
        unregisterReceiver();
        SuporApplication.getInstance().setPauseActivity(null);
        ActivityManager.finishAll();
        RxBus3.getInstance().unregister(this.getClass());
    }

}